<?php

/**
 * AmplifyCMS
 *
 * This file is part of AmplifyCMS.
 *
 * AmplifyCMS is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * AmplifyCMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @copyright Copyright 2008 Rodrigo Rutkoski Rodrigues
 */

/**
 *
 */
class Modules
{

  protected static $modules = array();

  /**
   *
   */
  public static function findAll($base, $path = '', $recursive = true)
  {
    $it = new DirectoryIterator($base . $path);
    
    $modules = array();
    
    while ($it->valid()) {
      if ($it->isDir() && ! $it->isDot() && strpos($it->getFilename(), '.') !== 0 && $recursive) {
        $modules += self::findAll($base, $path . '/' . $it->getFilename());
      }
      
      elseif (preg_match('/^(.+?)\_base_controller.php$/', $it->getFilename(), $o)) {
        $modules[$o[1]] = $base . $path . '/' . $it->getFilename();
      }
      
      $it->next();
    }
    
    return $modules;
  }

  /**
   *
   */
  public static function LoadActiveModules()
  {
    self::LoadModule(Simplify::getConfig()->get('{env}:home_dir') . '/options/options_amp_controller.php');
    self::LoadModule(Simplify::getConfig()->get('{env}:home_dir') . '/users/users_amp_controller.php');
    
    $modules = Options::value('amp_modules', array());
    
    if (! empty($modules)) {
      foreach ($modules as $path) {
        self::LoadModule($path, Simplify::getConfig()->get('{env}:app_dir') . '/modules');
      }
    }
  }

  /**
   *
   */
  protected static function LoadModule($file)
  {
    require_once ($file);
    
    $path = sy_fix_path(dirname($file));
    
    $name = basename($file, '_controller.php');
    $class = Inflector::camelize($name . '_controller');
    
    $module = new $class($path);
    
    $module->loadLanguageFile();
    
    Simplify::getL10n()->setTextDomain($module->getTextDomain());
    
    $module->buildMenu();
    
    Simplify::getL10n()->setTextDomain();
    
    self::$modules[$class] = $module;
  }

}

?>